#include "LogManager.h"
#include <fstream>
#include <filesystem>
#include <chrono>
#include <iomanip>
#include <sstream>

namespace fs = std::filesystem;

LogManager::LogManager()
{
    executor = std::make_unique<TaskExecutor>(1);
}

LogManager::~LogManager()
{
    flush();
}

LogManager &LogManager::getInstance()
{
    static LogManager instance;
    return instance;
}

void LogManager::init(const std::string &dir)
{
    logDir = dir;
    fs::create_directories(logDir);
}

void LogManager::log(const std::string &type, const std::string &message)
{
    std::ostringstream oss;
    auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    oss << "[" << std::put_time(std::localtime(&now), "%F %T")
        << "] [" << type << "] " << message << "\n";

    std::string fullMsg = oss.str();
    executor->submit([this, fullMsg]()
                     { writeToFile(fullMsg); });
}

void LogManager::writeToFile(const std::string &fullMsg)
{
    std::lock_guard<std::mutex> lock(mutex);
    std::string path = logDir + "/" + logFileName;
    std::ofstream ofs(path, std::ios::app);
    if (!ofs)
        return;
    ofs << fullMsg;
    ofs.close();
    rotate();
}

void LogManager::rotate()
{
    std::string path = logDir + "/" + logFileName;
    if (fs::exists(path) && fs::file_size(path) > maxFileSize)
    {
        for (int i = maxBackup - 1; i >= 1; --i)
        {
            std::string oldName = logDir + "/log_" + std::to_string(i) + ".txt";
            std::string newName = logDir + "/log_" + std::to_string(i + 1) + ".txt";
            if (fs::exists(oldName))
                fs::rename(oldName, newName);
        }
        fs::rename(path, logDir + "/log_1.txt");
    }
}

void LogManager::flush()
{
    executor.reset(); // 等待线程池任务完成
}
